<?php

/*
 * This file is part of ibrand/EC-Open-Server.
 *
 * (c) iBrand <https://www.ibrand.cc>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace iBrand\EC\Open\Server\Http\Controllers;

use Carbon\Carbon;
use Cart;
use DB;
use iBrand\Component\Address\RepositoryContract as AddressRepository;
use iBrand\Component\Discount\Applicators\DiscountApplicator;
use iBrand\Component\Discount\Models\Coupon;
use iBrand\Component\Discount\Models\Discount;
use iBrand\Component\Discount\Repositories\CouponRepository;
use iBrand\Component\Order\Models\Comment;
use iBrand\Component\Order\Models\Order;
use iBrand\Component\Order\Models\OrderItem;
use iBrand\Component\Order\Repositories\OrderRepository;
use iBrand\Component\Point\Repository\PointRepository;
use iBrand\Component\Product\Repositories\GoodsRepository;
use iBrand\Component\Product\Repositories\ProductRepository;
use iBrand\Component\Shipping\Models\Shipping;
use iBrand\EC\Open\Core\Applicators\PointApplicator;
use iBrand\EC\Open\Core\Processor\OrderProcessor;
use iBrand\EC\Open\Core\Services\DiscountService;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Redis;

class ShoppingController extends Controller
{
    private $goodsRepository;
    private $productRepository;
    private $discountService;
    private $orderRepository;
    private $discountApplicator;
    private $couponRepository;
    private $addressRepository;
    private $orderProcessor;
    private $pointRepository;
    private $pointApplicator;


    public function __construct(GoodsRepository $goodsRepository
        , ProductRepository $productRepository
        , DiscountService $discountService
        , OrderRepository $orderRepository
        , CouponRepository $couponRepository
        , DiscountApplicator $discountApplicator
        , AddressRepository $addressRepository
        , OrderProcessor $orderProcessor
        , PointRepository $pointRepository
        , PointApplicator $pointApplicator
    )
    {
        $this->goodsRepository = $goodsRepository;
        $this->productRepository = $productRepository;
        $this->discountService = $discountService;
        $this->orderRepository = $orderRepository;
        $this->discountApplicator = $discountApplicator;
        $this->couponRepository = $couponRepository;
        $this->addressRepository = $addressRepository;
        $this->orderProcessor = $orderProcessor;
        $this->pointRepository = $pointRepository;
        $this->pointApplicator = $pointApplicator;
    }

    public function checkout()
    {
        $user = request()->user();

        $cartItems = $this->getSelectedItemFromCart();

        if (0 == $cartItems->count()) {
            return $this->failed('未选中商品，无法提交订单');
        }

        $order = new Order(['user_id' => request()->user()->id]);

        //2. 生成临时订单对象
        $order = $this->buildOrderItemsFromCartItems($cartItems, $order);

        $defaultAddress = $this->addressRepository->getDefaultByUser(request()->user()->id);

        if (!$order->save()) {
            return $this->failed('订单提交失败，请重试');
        }

        //3.get available discounts
        list($discounts, $bestDiscountAdjustmentTotal, $bestDiscountId) = $this->getOrderDiscounts($order);

        //4. get available coupons
        list($coupons, $bestCouponID, $bestCouponAdjustmentTotal) = $this->getOrderCoupons($order, $user);

        //5. get point for order.
        //$orderPoint = $this->getOrderPoint($order, $user);

        //6.生成运费
        $order->payable_freight = 0;

        return $this->success([
            'order' => $order,
            'discounts' => $discounts,
            'coupons' => $coupons,
            'address' => $defaultAddress,
            'orderPoint' => 0,
            'best_discount_id' => $bestDiscountId,
            'best_coupon_id' => $bestCouponID,
            'best_coupon_adjustment_total' => $bestCouponAdjustmentTotal,
            'best_discount_adjustment_total' => $bestDiscountAdjustmentTotal,
        ]);
    }



    public function addOrder(){
        $user = request()->user();
        $arrays = request()->all();
        //var_dump($arrays);
        $at_id = 0;
        $is_goods = 0;
        $freight = get_freight();
        $is_distribution = 0;
        if(!is_array($arrays)){
            return $this->failed('缺少商品信息！');
        }
        if(!$arrays['address_id']){
            return $this->failed('缺少地址信息！');
        }
        $total = 0;
        $distribution_total = 0;
        $distribution_money = 0;
        $discount_money = 0;
        $action_money = 0;
        $count = 0;
        //1.购物车 3.拼团4.新人订单
        //如果存在分销人员的id，则计算分成
        $user_ids = (isset($arrays['user_id']) && !empty($arrays['user_id']))?$arrays['user_id']:0;
        if($user_ids){
            //查询用户是否是分销人员
            $ress = DB::table('good_girl')->where(['user_id'=>$user_ids,'status'=>1])->first();
            if(!$ress) fun_respon(0, '订单信息错误！');
            $is_distribution = 1;
        }
        //类型
        $type = (isset($arrays['type']))?$arrays['type']:0;
        foreach ($arrays['goods_info'] as $value){
            if(!$value['sku'] || !$value['id']) fun_respon(0, '商品信息错误！');
            $goods_detail = DB::table('ibrand_goods_product')->where(['goods_id'=>$value['id'],'sku'=>$value['sku']])->first(['spec_ids','sell_price']);
            if(!$goods_detail){
                return $this->failed('系统繁忙请重试');
            }
            //判断是否有分销
            if($is_distribution){
                $ress = DB::table('user_distribution')->where(['user_id'=>$user_ids,'is_valid'=>1,'goods_id'=>$value['id']])->first();
                if($ress){
                    $distribution_money = $ress->distribution_money;
                }
            }
            $price = $goods_detail->sell_price;
            //说明是拼团订单
            if($type==3){
                if(empty($arrays['goods_info'][0]['ac_id'])){
                    return $this->failed('缺少参数');
                }
                $ac_id = $arrays['goods_info'][0]['ac_id'];
                $activity_infos = DB::table('activity')->where(['is_valid'=>1,'ac_id'=>$ac_id])->first();
                //拼团运费
                $freight = $activity_infos->freight;
                $activity_goods_info = DB::table('activity_goods')->where(['goods_id'=>$value['id'],'sku'=>$value['sku'],'activity_id'=>$ac_id])->first();
                $price = $activity_goods_info->activity_price;

            }elseif($type==4){  //说明是新人订单
                $goods_info = DB::table('ibrand_goods')->where(['id'=>$value['id']])->first();
                $price = $goods_info->newcomer_price;
            }
            //计算价格和数量
            $count += $value['num'];
            $sum = $value['num'] * $price;
            $distribution_sum = $value['num'] * $distribution_money;
            $total += $sum;
            $distribution_total += $distribution_sum;
            //判断优惠券
            if($type!=4 && $type!=3){
                //判断是否有优惠券
                $coupon_code = (isset($arrays['coupon_code']) && !empty($arrays['coupon_code']))?$arrays['coupon_code']:'';
                if($coupon_code){
                    //查询优惠券
                    $result = DB::table('ibrand_discount_coupon')->where(['code'=>$arrays['coupon_code']])->where('used_at','=',NULL)->first();
                    if(!$result){
                        return $this->failed('优惠券信息错误！');
                    }
                    //查询优惠
                    $action = DB::table('ibrand_discount_action')->where(['discount_id'=>$result->discount_id])->first();
                    $aconfiguration = (json_decode($action->configuration,true));
                    $action_money = $aconfiguration['amount'];
                    //查询规则
                    $rules = DB::table('ibrand_discount_rule')->where(['discount_id'=>$result->discount_id])->get();
                    foreach ($rules as $v){
                        $configuration = json_decode($v->configuration,true);
                        if($v->type=='item_total'){
                            $discount_money = $configuration['amount'];
                        }elseif ($v->type=='contains_product'){
                            $spus = explode(',',$configuration['spu']);
                            if(in_array($value['id'],$spus)){
                                $is_goods = 1;
                            }
                        }
                    }
                }
            }
        }
        $items_total = $total;
        if($total<=30 && $type!=4){
            $totals = $total + $freight;
            //$totals = $total;
            $real_freight = $freight*100;
        }else{
            $totals = $total;
            $real_freight = 0;
        }
        $totals = $totals*100;

        //var_dump($discount_money);
        //var_dump($is_goods);

        //var_dump($discount_money || $is_goods==1);

        //扣减优惠金额
        if($discount_money || $is_goods==1){
            if($totals >= $discount_money){
                $totals = $totals - $action_money;
            }else{
                return $this->failed('订单金额有误！！');
            }
        }
        $address = $this->addressRepository->find($arrays['address_id']);
        if(!$address){
            return $this->failed('地址信息错误！');
        }
        try{
            DB::beginTransaction();
            $goods_id = $arrays['goods_info'][0]['id'];
            $sku = $arrays['goods_info'][0]['sku'];
            //写入参与拼团的信息
            if($type ==3 ){
                //判断是时间 如果时间超过不允许付款
                if(time() >= strtotime($activity_infos->end_time)){
                    return $this->failed('拼团活动已结束！');
                }
                $at_id = $arrays['goods_info'][0]['at_id'];
                //判断活动是否可以重复购买 如果不可以直接走正常的流程 如果可以判断是否有已经完成的拼团
                if($activity_infos->is_repeat==1 && $activity_infos->team_num==0){
                    $res = DB::table('activity_users')->where(['user_id'=>$user->id,'ac_id'=>$activity_infos->ac_id,'activity_goods_id'=>$goods_id])->first();
                    if($res){
                        //如果存在成功的 说明上次的已经成团了这次可以购买 如果不存在
                        $activity_team = DB::table('activity_team')->where(['is_succeed'=>1,'at_id'=>$res->at_id])->first();
                        if(!$activity_team){
                            return $this->failed('您已经参加拼团了！');
                        }
                    }
                }else{
                    //设置成团数 判断一下是否满了
                    if($activity_infos->team_num > 0){
                        $res = DB::select("SELECT activity_users.ac_id,COUNT(*) AS ac_num FROM `activity_team` LEFT JOIN activity_users ON activity_users.at_id = activity_team.at_id WHERE activity_team.ac_id = ? GROUP BY activity_users.at_id HAVING ac_num >= ?",[$activity_infos->ac_id,$activity_infos->activity_num]);
                        $team_num = count($res);
                        if($team_num >= $activity_infos->team_num){
                            return $this->failed('拼团名额已满！');
                        }
                        /*$activity_team = DB::table('activity_team')->where(['ac_id'=>$activity_infos->ac_id])->get();
                        $num = count($activity_team);
                        if($num >= $activity_infos->team_num){
                            return $this->failed('拼团名额已满！');
                        }*/
                    }

                    $activity_users_info = DB::table('activity_users')->where(['user_id'=>$user->id,'activity_goods_id'=>$goods_id,'sku'=>$sku,'ac_id'=>$activity_infos->ac_id])->first();
                    if($activity_users_info){
                        return $this->failed('您已经参加过拼团了！');
                    }

                    $activity_users = DB::table('activity_users')->where(['at_id'=>$at_id])->get();
                    $nums = count($activity_users);
                    //如果小于
                    if($nums >= ($activity_infos->activity_num)){
                        return $this->failed('队伍已满不能参加！');
                    }
                }
                $str = $user->id.'_'.$goods_id.'_'.$sku.'_'.$at_id.'_'.$activity_infos->ac_id;
                $res = DB::table('ibrand_order')->where(['user_id'=>$user->id,'type'=>1,'channel'=>$str,'status'=>1,'is_valid'=>0])->first();
                if($res){
                    return $this->success(['order_id'=>$res->order_no]);
                }
            }elseif($type ==4){
                $str = $user->id.'_'.$goods_id.'_'.$sku;
                $res = DB::table('ibrand_order')->where(['user_id'=>$user->id,'type'=>2,'channel'=>$str,'status'=>1,'is_valid'=>0])->first();
                if($res){
                    return $this->success(['order_id'=>$res->order_no]);
                }
            }else{
                if($action_money > 0){
                    DB::table('ibrand_discount_coupon')->where(['code'=>$arrays['coupon_code']])->update(['used_at'=>Carbon::now()]);
                }
            }

            if($type==3){
                $types=1;
            }elseif ($type==4){
                $types=2;
            }else{
                $types=0;
            }
            //写入订单信息
            $order_no = build_order_no();
            $arr['order_no'] = $order_no;
            $arr['user_id'] = $user->id;
            $arr['status'] = 1;
            $arr['items_total'] = $items_total*100;
            $arr['total'] = $totals;
            $arr['count'] = $count;
            $arr['real_freight'] = $real_freight;
            $arr['accept_name'] = $address->accept_name;
            $arr['type'] = $types;
            $arr['channel'] = ($type==3 || $type==4)?$str:'';
            $arr['is_valid'] = ($type==3 || $type==4)?0:1;
            $arr['mobile'] = $address->mobile;
            $arr['address'] = $address->address;
            $arr['coupon_code'] = $action_money >0?$arrays['coupon_code']:'';
            $arr['address_name'] = $address->address_name;
            $arr['adjustments_total'] = $action_money >0?$action_money:0;
            $arr['created_at'] = date('Y-m-d H:i:s',time());
            $arr['message'] = isset($arrays['note'])?$arrays['note']:'';
            $arr['agent_id'] = $is_distribution==1?$user_ids:0;
            $arr['distribution_total'] = $is_distribution?$distribution_total:0;
            $res = DB::table('ibrand_order')->insertGetId($arr);
            foreach ($arrays['goods_info'] as $items){
                $goods_detail = DB::table('ibrand_goods_product')->leftjoin('ibrand_goods','ibrand_goods.id','=','ibrand_goods_product.goods_id')->where(['goods_id'=>$items['id'],'sku'=>$items['sku']])->first(['name','spec_ids','ibrand_goods_product.sell_price']);
                $item['order_id'] = $res;
                $item['item_id'] = $items['id'];
                $item['item_name'] = $goods_detail->name;
                $item['type'] = 'iBrand\Component\Product\Models\Product';
                $item['sku'] = $items['sku'];
                $item_meta = ['image'=>$items['goods_img'],'detail_id'=>$items['id'],'specs_text'=>$items['sku_name']];
                $item['item_meta'] = json_encode($item_meta);
                $item['quantity'] = $items['num'];
                $item['unit_price'] = $goods_detail->sell_price*100;
                $item['units_total'] = $goods_detail->sell_price*$items['num']*100;
                $item['adjustments_total'] = 0;
                $item['total'] = $item['units_total'];
                $item['created_at'] = date('Y-m-d H:i:s',time());
                $order_item[] = $item;
            }
            //插入详情
            DB::table('ibrand_order_item')->insert($order_item);
            //移除购物车里面的商品
            if(isset($arrays['type']) && $arrays['type']==1){
                $key = 'cart_'.$user->id;
                $goods_info = Redis::get($key);
                if(!$goods_info){
                    return $this->failed('暂无商品！');
                }
                $goods_infos = json_decode($goods_info,true);
                $skus = array_column($goods_infos, 'sku');
                foreach ($arrays['goods_info'] as $v){
                    $found_key = array_search($v['sku'],$skus );
                    if($found_key===false){
                        return $this->failed('暂无商品！');
                    }
                    unset($goods_infos[$found_key]);
                    $goods_infoss =  array_values($goods_infos);
                }
                $cart_list = json_encode($goods_infoss);
                Redis::set($key,$cart_list);
            }
            DB::commit();
            return $this->success(['order_id'=>$order_no]);
        }catch (\Exception $exception) {
            DB::rollBack();
            //\Log::info($exception->getMessage() . $exception->getTraceAsString());
            var_dump($exception->getMessage() . $exception->getTraceAsString());
            return $this->failed('订单提交失败');
        }



    }


    /**
     * confirm the order to be waiting to pay.
     */
    public function confirm()
    {
        $user = request()->user();

        $order_no = request('order_no');
        if (!$order_no || !$order = $this->orderRepository->getOrderByNo($order_no)) {
            return $this->failed('订单不存在');
        }

        if ($user->cant('submit', $order)) {
            return $this->failed('订单提交失败，无权操作');
        }

        if ($note = request('note')) {
            $order->note = $note;
        }

        //1. check stock.
        foreach ($order->getItems() as $item) { // 再次checker库存
            $model = $item->getModel();

            if (!$model->getIsInSale($item->quantity)) {
                return $this->failed('商品: ' . $item->name . ' ' . $item->item_meta['specs_text'] . ' 库存不够，请重新下单');
            }
        }

        try {
            DB::beginTransaction();
            //2. apply the available discounts
            $discount = Discount::find(request('discount_id'));
            if (!empty($discount)) {
                if ($this->discountService->checkDiscount($order, $discount)) {
                    $order->type = Order::TYPE_DISCOUNT;

                    $this->discountApplicator->apply($order, $discount);
                } else {
                    return $this->failed('折扣信息有误，请确认后重试');
                }
            }
            //3. apply the available coupons
            if (empty($discount) or 1 != $discount->exclusive) {

                $coupon = Coupon::find(request('coupon_id'));
                if (!empty($coupon)) {
                    if (null != $coupon->used_at) {
                        return $this->failed('此优惠券已被使用');
                    }
                    if ($user->can('update', $coupon) and $this->discountService->checkCoupon($order, $coupon)) {
                        $this->discountApplicator->apply($order, $coupon);
                    } else {
                        return $this->failed('优惠券信息有误，请确认后重试');
                    }
                }
            }

            //4. use point
            if ($point = request('point') && config('ibrand.app.point.enable')) {
                if ($this->checkUserPoint($order, $point)) {
                    $this->pointApplicator->apply($order, $point);
                } else {
                    return $this->failed('积分不足或不满足积分折扣规则');
                }
            }

            //5. 保存收获地址信息。
            if (request('address_id') && $address = $this->addressRepository->find(request('address_id'))) {
                $order->accept_name = $address->accept_name;
                $order->mobile = $address->mobile;
                $order->address = $address->address;
                $order->address_name = $address->address_name;
            }

            //5. 保存订单状态
            $this->orderProcessor->submit($order);


            //6. remove goods store.
            foreach ($order->getItems() as $item) {
                $product = $item->getModel();
                $product->reduceStock($item->quantity);
                $product->increaseSales($item->quantity);
                $product->save();
            }

            //8. 移除购物车中已下单的商品
            foreach ($order->getItems() as $orderItem) {
                if ($carItem = Cart::search(['name' => $orderItem->item_name])->first()) {
                    Cart::remove($carItem->rawId());
                }
            }

            DB::commit();

            return $this->success(['order' => $order], true);

        } catch (\Exception $exception) {
            DB::rollBack();
            \Log::info($exception->getMessage() . $exception->getTraceAsString());

            return $this->failed('订单提交失败');
        }
    }

    /**
     * cancel this order.
     */
    public function cancel()
    {
        $user = request()->user();

        $order_no = request('order_no');
        if (!$order_no || !$order = $this->orderRepository->getOrderByNo($order_no)) {
            return $this->failed('订单不存在');
        }

        if ($user->cant('cancel', $order)) {
            return $this->failed('无法取消该订单');
        }

        $this->orderProcessor->cancel($order);

        //TODO: 用户未付款前取消订单后，需要还原库存
        foreach ($order->getItems() as $item) {
            $product = $item->getModel();
            $product->restoreStock($item->quantity);
            $product->restoreSales($item->quantity);
            $product->save();
        }

        return $this->success();
    }

    /**
     * received this order.
     */
    public function received()
    {
        try {
            DB::beginTransaction();

            $user = request()->user();

            $order_no = request('order_no');
            if (!$order_no || !$order = $this->orderRepository->getOrderByNo($order_no)) {
                return $this->failed('订单不存在');
            }

            if ($user->cant('received', $order)) {
                return $this->failed('无法对此订单进行确认收货操作');
            }

            $order->status = Order::STATUS_RECEIVED;
            $order->accept_time = Carbon::now();
            $order->save();

            DB::commit();

            return $this->api([], true, 200, '确认收货操作成功');
        } catch (\Exception $exception) {
            DB::rollBack();
            \Log::info($exception->getMessage() . $exception->getTraceAsString());
            $this->response()->errorInternal($exception->getMessage());
        }
    }

    public function delete()
    {
        $user = request()->user();

        $order_no = request('order_no');
        if (!$order_no || !$order = $this->orderRepository->getOrderByNo($order_no)) {
            return $this->failed('订单不存在');
        }

        if ($user->cant('delete', $order)) {
            return $this->failed('无权删除此订单');
        }

        $order->status = Order::STATUS_DELETED;
        $order->save();

        return $this->success();
    }



    public function reviews(){
        $user = request()->user();
        $comments = request()->except('_token');
        //var_dump($comments);
        if (!($comments)) {
            return $this->failed('提交参数错误');
        }

        if (!isset($comments['order_no']) or !$order = $this->orderRepository->getOrderByNo($comments['order_no'])) {
            return $this->failed('订单 ' . $comments['order_no'] . ' 不存在');
        }
        if(!$comments['goods_id']){
            return $this->failed('提交参数错误');
        }
        $order_item_info = DB::table('ibrand_order_item')->where(['order_id'=>$order->id,'item_id'=>$comments['goods_id']])->first();
        if (!isset($order_item_info->id) or !$orderItem = OrderItem::find($order_item_info->id)) {
            return $this->failed('请选择具体评价的商品');
        }
        /*if ($user->cant('review', [$order, $orderItem])) {
            return $this->failed('无权对该商品进行评价');
        }*/
        if($order->user_id!=$user->id){
            return $this->failed('无权对该商品进行评价');
        }
        if ($order->comments()->where('order_item_id', $order_item_info->id)->count() > 0) {
            return $this->failed('该产品已经评论，无法再次评论');
        }

        $content = isset($comments['contents']) ? $comments['contents'] : '';
        $point = isset($comments['point']) ? $comments['point'] : 5;
        $pic_list = isset($comments['images']) ? $comments['images'] : [];

        $comment = new Comment(['user_id' => $user->id, 'order_item_id' => $order_item_info->id, 'item_id' => $orderItem->item_id, 'item_meta' => $orderItem->item_meta, 'contents' => $content, 'point' => $point, 'status' => 'hidden', 'pic_list' => $pic_list, /*'goods_id' => $orderItem->item_meta['detail_id']*/]);

        $order->comments()->save($comment);

        //$order->status = Order::STATUS_COMPLETE;
        $order->completion_time = Carbon::now();
        $order->save();
        return $this->success('评价成功');
    }


    public function review()
    {
        $user = request()->user();
        $comments = request()->except('_token');

        if (!is_array($comments)) {
            return $this->failed('提交参数错误');
        }

        foreach ($comments as $key => $comment) {
            if (!isset($comment['order_no']) or !$order = $this->orderRepository->getOrderByNo($comment['order_no'])) {
                return $this->failed('订单 ' . $comment['order_no'] . ' 不存在');
            }

            if (!isset($comment['order_item_id']) or !$orderItem = OrderItem::find($comment['order_item_id'])) {
                return $this->failed('请选择具体评价的商品');
            }

            if ($user->cant('review', [$order, $orderItem])) {
                return $this->failed('无权对该商品进行评价');
            }

            if ($order->comments()->where('order_item_id', $comment['order_item_id'])->count() > 0) {
                return $this->failed('该产品已经评论，无法再次评论');
            }

            $content = isset($comment['contents']) ? $comment['contents'] : '';
            $point = isset($comment['point']) ? $comment['point'] : 5;
            $pic_list = isset($comment['images']) ? $comment['images'] : [];

            $comment = new Comment(['user_id' => $user->id, 'order_item_id' => $comment['order_item_id'], 'item_id' => $orderItem->item_id, 'item_meta' => $orderItem->item_meta, 'contents' => $content, 'point' => $point, 'status' => 'show', 'pic_list' => $pic_list, 'goods_id' => $orderItem->item_meta['detail_id'],
            ]);

            $order->comments()->save($comment);

            $order->status = Order::STATUS_COMPLETE;
            $order->completion_time = Carbon::now();
            $order->save();
        }

        return $this->success();
    }

    /**
     * call by call_user_func().
     *
     * @return bool|Collection
     *
     * @throws \Exception
     */
    private function getSelectedItemFromCart()
    {
        //获取购物车中选中的商品数据
        $ids = request('cart_ids');

        $cartItems = new Collection();

        if (!$ids || 0 == count($ids)) {
            return $cartItems;
        }

        foreach ($ids as $cartId) {
            if ($cart = Cart::get($cartId)) {
                $cartItems->put($cartId, $cart);
            }
        }

        foreach ($cartItems as $key => $item) {
            //检查库存是否足够
            if (!$this->checkItemStock($item)) {
                Cart::update($key, ['message' => '库存数量不足', 'status' => 'onhand']);

                throw new \Exception('商品: ' . $item->name . ' ' . $item->color . ',' . $item->size . ' 库存数量不足');
            }
        }

        return $cartItems;
    }

    private function checkItemStock($item)
    {
        if (is_null($item->model) || !$item->model->getIsInSale($item->qty)) {
            return false;
        }

        return true;
    }

    /**
     * get order discounts data.
     *
     * @param $order
     *
     * @return array
     */
    private function getOrderDiscounts($order)
    {
        $bestDiscountAdjustmentTotal = 0;
        $bestDiscountId = 0;

        $discounts = $this->discountService->getEligibilityDiscounts($order);

        if ($discounts) {
            if (0 == count($discounts)) { //修复过滤后discount为0时非false 的问题。
                $discounts = false;
            } else {
                $bestDiscount = $discounts->sortBy('adjustmentTotal')->first();
                $bestDiscountId = $bestDiscount->id;
                $bestDiscountAdjustmentTotal = -$bestDiscount->adjustmentTotal;
                $discounts = collect_to_array($discounts);
            }
        }

        return [$discounts, $bestDiscountAdjustmentTotal, $bestDiscountId];
    }

    /**
     * @param $order
     * @param $user
     *
     * @return array|bool
     */
    private function getOrderCoupons($order, $user)
    {
        $bestCouponID = 0;
        $bestCouponAdjustmentTotal = 0;
        $cheap_price = 0;

        $coupons = $this->discountService->getEligibilityCoupons($order, $user->id);

        if ($coupons) {
            $bestCoupon = $coupons->sortBy('adjustmentTotal')->first();
            if ($bestCoupon->orderAmountLimit > 0 and $bestCoupon->orderAmountLimit > ($order->total + $cheap_price)) {
                $bestCouponID = 0;
            } else {
                $bestCouponID = $bestCoupon->id;
                $cheap_price += $bestCoupon->adjustmentTotal;
                $bestCouponAdjustmentTotal = -$bestCoupon->adjustmentTotal;
            }

            $coupons = collect_to_array($coupons);
        } else {
            $coupons = [];
        }

        return [$coupons, $bestCouponID, $bestCouponAdjustmentTotal];
    }

    /**
     * @param $cartItems
     * @param $order
     *
     * @return OrderItem
     */
    private function buildOrderItemsFromCartItems($cartItems, $order)
    {
        foreach ($cartItems as $key => $item) {
            if (0 == $item->qty) {
                continue;
            }

            $item_meta = [
                'image' => $item->img,
                'detail_id' => $item->model->detail_id,
                'specs_text' => $item->model->specs_text,
            ];

            $orderItem = new OrderItem(['quantity' => $item->qty, 'unit_price' => $item->model->sell_price,
                'item_id' => $item->id, 'type' => $item->__model, 'item_name' => $item->name, 'item_meta' => $item_meta,
            ]);

            $orderItem->recalculateUnitsTotal();

            $order->addItem($orderItem);
        }

        return $order;
    }

    public function delivery()
    {
        $order_no = request('order_no');

        $order = $this->orderRepository->getOrderByNo($order_no);

        if (!$order_no || !$order || 2 != $order->status) {
            return $this->response()->errorBadRequest('订单不存在');
        }

        $data['delivery_time'] = date('Y-m-d H:i:s', Carbon::now()->timestamp);

        $data['order_id'] = $order->id;

        $data['method_id'] = mt_rand(1, 10);

        $data['tracking'] = uniqid();

        if (Shipping::create($data)) {

            $order->status = 3;
            $order->save();
            return $this->success();
        }

        return $this->failed('订单发货失败');
    }

    private function getOrderPoint($order, $user)
    {
        if (config('ibrand.app.point.enable')) {
            //$orderPoint['userPoint'] = $this->pointRepository->getSumPointValid($user->id); //用户可用积分
            $orderPoint['pointToMoney'] = config('ibrand.app.point.order_proportion');  //pointToMoney
            $orderPoint['pointLimit'] = config('ibrand.app.point.order_limit') / 100; //pointLimit
            $pointAmount = min($orderPoint['userPoint'] * $orderPoint['pointToMoney'], $order->total * $orderPoint['pointLimit']);
            $orderPoint['pointAmount'] = -$pointAmount;
            $orderPoint['pointCanUse'] = $pointAmount / $orderPoint['pointToMoney'];
        }
    }


    /**
     * confirm user point can be used in this order.
     * @param $order
     * @param $point
     * @return bool
     */
    private function checkUserPoint($order, $point)
    {
        $userPoint = $this->pointRepository->getSumPointValid($order->user_id);
        $usePointAmount = $point * config('ibrand.app.point.order_proportion');
        $orderPointLimit = $order->total * config('ibrand.app.point.order_limit');

        //如果用户的积分小于使用的积分 或者抵扣的金额大于了订单可抵扣金额，则无法使用该积分
        if ($userPoint < $point || $usePointAmount > $orderPointLimit) {
            return false;
        }

        return true;
    }
}
